<template>
  <div style="width: 100vw;height: 100vh;display: flex;flex-direction: column;overflow: hidden;">
    <div style="height: 10vh; background-color: #f5f5f5; min-height: 60px; flex-shrink: 0;">
      <el-row :gutter="10">
        <el-col :span="1">
          <img src="../../../public/imgs/login/leaf.png" style="height: 40px; padding-top: 13px; padding-left: 16px;">
        </el-col>
        <el-col :span="15">
          <span style="font-size: 25px; color: #35984b; padding-left: 40px; line-height: 10vh;font-weight: bold;">垃圾分类管理项目后台</span>
        </el-col>
      </el-row>
    </div>

    <div style="display: flex; height: 90vh;">
      <!-- 左侧菜单栏 -->
      <div style="width: 228px">
        <el-menu
            background-color="#35984b"
            style="width: 100%; height: 100vh; border: none;"
            text-color="#fff"
            active-text-color="#fff"
            router
            :collapse-transition="true"
        >
          <el-menu-item index="/adminNotice">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Promotion /></el-icon>
              <span class="left-menu-item">资讯管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminGarbage">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><DeleteFilled /></el-icon>
              <span class="left-menu-item">垃圾管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminUser">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><UserFilled /></el-icon>
              <span class="left-menu-item">用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminPut">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><CircleCheckFilled /></el-icon>
              <span class="left-menu-item">投放管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/admin">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Avatar /></el-icon>
              <span class="left-menu-item">个人中心</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧顶部条与主体内容（可变区域）-->
      <div style="width: calc(100% - 228px)">
        <el-header style="height: 80px; background-color: #fff; padding-top: 22px;">
          <el-row>
            <!-- 登录人姓名和退出登录 -->
            <el-col :span="24">
              <div style="display: flex; justify-content: space-between; align-items: center; height: 100%; padding:0 20px;">
                <!-- 面包屑导航 -->
                <el-breadcrumb separator="/" style="margin-left: 10px;">
                  <el-breadcrumb-item
                      v-for="item in breadcrumb"
                      style="font-size: 16px; font-weight: 500;"
                  >
                    | {{ item }}
                  </el-breadcrumb-item>
                </el-breadcrumb>

                <!-- 用户信息 -->
                <div>
                  <el-dropdown trigger="click">
                    <div style="display: flex; align-items: center; cursor: pointer; padding: 8px 12px; border-radius: 4px;">
                      <el-icon><User /></el-icon>
                      <span style="font-size: 16px; font-weight: 500; color: #606266; margin-left: 8px; margin-right: 8px;">{{ user.username }}</span>
                      <el-icon><ArrowDown /></el-icon>
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu style="--el-dropdown-menuItem-hover-fill: #f6f6f6; --el-dropdown-menuItem-hover-color: #008800;">
                        <el-dropdown-item @click="toAdmin">
                          <el-icon><Avatar /></el-icon>个人中心
                        </el-dropdown-item>
                        <el-dropdown-item @click="logout" divided>
                          <el-icon><SwitchButton /></el-icon>退出登录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-header>
        <!-- 右侧主体内容 -->
        <el-main style=" padding: 0; height: calc(100vh - 10vh - 100px); overflow-y: auto;">
          <!-- 资讯搜索卡片 -->
          <el-card style="margin: 10px;height: 70px;">
            <el-form :inline="true">
              <el-form-item label="资讯标题" style="width: 270px;">
                <el-input placeholder="请输入资讯标题" v-model="searchNoticeForm.title"></el-input>
              </el-form-item>
              <el-form-item label="资讯类别" style="width: 290px;">
                <el-select placeholder="请选择资讯类别" v-model="searchNoticeForm.category">
                  <el-option label="通告" value="通告"></el-option>
                  <el-option label="公告" value="公告"></el-option>
                  <el-option label="新闻" value="新闻"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="info" @click="resetSearch">重置</el-button>
                <el-button type="success" @click="loadNotice">搜索</el-button>
              </el-form-item>
              <el-form-item style="float: right; margin-bottom: 20px;">
                <el-button type="success" style="float:right;"
                           @click="beforeAddNotice">添加资讯</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <!-- 添加资讯弹窗 -->
          <el-dialog
              :title="dialogTitle"
              style="width:600px;padding:40px;"
              v-model="dialogVisible"
              :before-close="handleClose"
          >
            <el-form label-position="top" label-width="80">
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item label="标题">
                    <el-input placeholder="请输入资讯标题" v-model="saveNoticeForm.title"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item label="内容">
                    <el-input type="textarea" :rows="10" placeholder="请输入资讯内容" v-model="saveNoticeForm.content"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item label="资讯来源">
                    <el-input placeholder="请输入资讯来源" v-model="saveNoticeForm.resources"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item label="类别">
                    <el-select placeholder="请选择类别" v-model="saveNoticeForm.category">
                      <el-option label="通告" value="通告"></el-option>
                      <el-option label="公告" value="公告"></el-option>
                      <el-option label="新闻" value="新闻"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <el-button type="info" @click="handleClose">取消</el-button>
              <el-button type="success" @click="saveNotice">保存</el-button>
            </template>
          </el-dialog>
          <!-- 资讯表格卡片 -->
          <el-card style="margin: 10px;">
            <el-table :data="pagedNoticeArr">
              <el-table-column type="index" label="序号" width="60" align="center">
                <template #default="scope">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="title" label="资讯标题" align="center"></el-table-column>
              <el-table-column prop="category" label="资讯类别" align="center"></el-table-column>
              <el-table-column prop="content" label="资讯内容" align="center">
                <template #default="{row}">
                  <div class="content-cell">
                    {{ row.content }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="resources" label="资讯来源" align="center"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
              <el-table-column prop="updateTime" label="更新时间" align="center"></el-table-column>
              <el-table-column prop="createBy" label="发布人id" width="60" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="primary" link @click="viewNotice(scope.row)">查看</el-button>
                  <el-button type="success" link @click="editNotice(scope.row.id)">编辑</el-button>
                  <el-button type="danger" link @click="deleteNotice(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 查看详情的 Dialog -->
            <el-dialog
                v-model="detailVisible"
                title="资讯详情"
                width="60%"
                :close-on-click-modal="false">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="资讯标题">{{ currentNotice.title }}</el-descriptions-item>
                <el-descriptions-item label="资讯类别">{{ currentNotice.category }}</el-descriptions-item>
                <el-descriptions-item label="资讯内容">
                  <div style="white-space: pre-line;">{{ currentNotice.content }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="资讯来源">{{ currentNotice.resources }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ currentNotice.createTime }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ currentNotice.updateTime }}</el-descriptions-item>
                <el-descriptions-item label="发布人ID">{{ currentNotice.createBy }}</el-descriptions-item>
              </el-descriptions>

              <template #footer>
                <el-button type="info" @click="detailVisible = false">关闭</el-button>
              </template>
            </el-dialog>

            <!-- 分页组件 -->
            <div style="padding: 20px 0; text-align: center;">
              <el-pagination
                  layout="prev, pager, next"
                  :total="noticeArr.length"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
              />
            </div>
          </el-card>

        </el-main>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Message,
  Delete,
  User,
  Avatar,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'
import axios from "axios";
import qs from "qs";

// 获取当前登录用户的信息
const user = ref(getUser());

const toAdmin = () => {
  router.push('/admin');
}

const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    localStorage.removeItem('user');
    window.location.href = '/login';
    user.value = '';
  }).catch(()=>{

  })
}

// 更新面包屑映射
let map = {
  '/adminNotice': ['资讯管理'],
  '/adminGarbage': ['垃圾管理'],
  '/admin': ['个人中心'],
  '/adminUser': ['用户管理'],
  '/adminPut': ['投放管理'],
}

const breadcrumb = ref([]);
const route = useRoute();
const router = useRouter();

onMounted(() => {
  updateBreadcrumb(route);
})

// 定义更新面包屑导航值的方法
const updateBreadcrumb = (route) => {
  const path = route.path;
  breadcrumb.value = map[path] || [];
}

// 监听路由变化，更新面包屑
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})

//定义对象用来保存用户搜索条件
const searchNoticeForm = ref({title:'', category:''});
//定义变量用来控制弹窗是否出现
const dialogVisible = ref(false);
//定义数组用来保存用户表格数据
const noticeArr = ref([]);
//定义加载用户数据的方法
const loadNotice = ()=>{
  let data = qs.stringify(searchNoticeForm.value);
  console.log(data);
  axios.get('http://localhost:8080/v1/notice/select?'+data).then((response)=>{
    if(response.data.code == 2000){
      noticeArr.value = response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
onMounted(()=>{
  loadNotice();
})
const resetSearch = ()=>{
  searchNoticeForm.value = {};
  loadNotice();
}
const dialogTitle = ref();
const beforeAddNotice = ()=>{
  dialogTitle.value = '添加资讯';
  dialogVisible.value = true;
}
const saveNoticeForm = ref({
  title:'',
  category:'',
  content:'',
  resources:'',
  createBy:user.value.id
});

const saveNotice = ()=>{
  console.log(saveNoticeForm.value);
  let data = qs.stringify(saveNoticeForm.value);
  axios.post('http://localhost:8080/v1/notice/save',data)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('保存成功!');
          dialogVisible.value = false;
          saveNoticeForm.value = {};
          loadNotice();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
const isEdit = ref(false);
//定义处理弹窗关闭的方法
const handleClose = () => {
  if (isEdit.value) {
    // 直接关闭
    saveNoticeForm.value = {};
    dialogVisible.value = false;
  } else {
    // 如果是添加状态才提示
    ElMessageBox.confirm('确定要放弃添加资讯吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      saveNoticeForm.value = {};
      dialogVisible.value = false;
    }).catch(() => {});
  }
};

// 控制对话框显示
const detailVisible = ref(false);
// 当前查看的资讯
const currentNotice = ref({});

// 查看资讯详情
const viewNotice = (notice) => {
  currentNotice.value = notice;
  detailVisible.value = true;
};

const editNotice = (id) => {
  dialogTitle.value = '编辑资讯';
  isEdit.value = true;
  dialogVisible.value = true;
  axios.get('http://localhost:8080/v1/notice/select?id='+id).then((response)=>{
    if(response.data.code == 2000){
      saveNoticeForm.value = response.data.data[0];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
const deleteNotice = (id) => {
  ElMessageBox.confirm('确定删除该资讯吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    axios.post('http://localhost:8080/v1/notice/delete/' + id)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除成功!');
            loadNotice(); // 删除成功后,需要重新加载用户列表数据!
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch((error) => {
          ElMessage.error('删除资讯时发生错误');
          console.error(error);
        });
  }).catch(() => {
  });
}


// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);

// 计算属性：返回当前页的数据
const pagedNoticeArr = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return noticeArr.value.slice(start, end);
});

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.left-menu-item {
  font-size: 18px;
  padding-left: 12px;
}

.left-menu-collapse-item {
  font-size: 17px;
  border: none;
  height: 40px;
}

.content-cell {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示三行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5; /* 设置合适的行高 */
  max-height: 4.5em; /* 三行的高度 (3 * line-height) */
}

/* 自定义滚动条样式 */
.el-main::-webkit-scrollbar {
  width: 8px;
}

.el-main::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.el-main::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
.el-pagination {
  justify-content: center;
}
</style>